import httpServeList from './httpServeList'
let app = getApp();

let $httpServer = function (opts, data) {
  let promise = new Promise(function (resolve, reject) {
    let parameterData = data
    let head = {
      // 'content-type': 'application/x-www-form-urlencoded'
      "Content-Type": "application/json",
      "DF-User-Token": app.globalData.token
    }
    // 判断是否携带token
    if (app.globalData.token == '') {
      delete head['DF-User-Token']
    }
    // 判断请求方式
    if (opts.method.toLowerCase() == 'post') {
      parameterData = JSON.stringify(parameterData)
    }
    return dd.httpRequest({
      headers: head,
      url: httpServeList.httpUrl + opts.url,
      method: opts.method,
      data: parameterData,
      dataType: 'json',
      success: function (res) {
        let code = res.data.code
        let message = res.data.message
        // 0："成功"，-1："系统繁忙"，2："验证失败"，886："token过期"，20003："企业没有授权开通应用"
        if (code == '0') {
          resolve(res.data)
        } else if (code == '-1') {
          dd.alert({ content: message });
        } else if (code == '2') {
          dd.alert({ content: message });
        } else if (code == '3') {
          dd.alert({ content: message });
        } else if (code == '886') {
          dd.alert({
            title: '提示',
            content: '登录过期，返回首页重新登录',
            buttonText: '确定',
            success: () => {
              dd.reLaunch({
                url: '/pages/index/index'
              })
            },
          });
        } else if (code == '20003') {
          dd.alert({ content: '企业没有授权开通应用' });
        }
      },
      fail: function (res) {
        console.log(res)
        dd.hideLoading();
        // dd.alert({ content: '服务请求失败' });
        reject(res)
      },
      complete: function (res) {
        dd.hideLoading();
      }
    });
  })
  return promise
}

export default $httpServer